package vip.george.p0073;


import java.util.HashSet;
import java.util.Set;

public class P73 {


    /**
     * 方法1：
     * 创建两个集合，分别记录行和列的索引，然后遍历矩阵，如果某个元素为0，则将行和列的索引加入集合中。最后遍历矩阵，如果行或列的索引在集合中，则将元素置为0。
     * @param matrix
     */
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        Set<Integer> rows = new HashSet<>();
        Set<Integer> cols = new HashSet<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    rows.add(i);
                    cols.add(j);
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (rows.contains(i) || cols.contains(j)) {
                    matrix[i][j] = 0;
                }
            }
        }
    }

    public static void main(String[] args) {
        P73 p73 = new P73();
        System.out.println("=======测试1===========");
        int[][] matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
        p73.display(matrix);
        p73.setZeroes(matrix);
        System.out.println("=======测试1结果========");
        p73.display(matrix);
        System.out.println();
        System.out.println("=======测试2==========");
        matrix = new int[][]{{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
        p73.display(matrix);
        p73.setZeroes(matrix);
        System.out.println("=======测试2结果========");
        p73.display(matrix);
    }

    public void display(int[][] matrix) {
        for (int[] its : matrix) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(its[j] + " ");
            }
            System.out.println();
        }
    }
}
